package com.miqtech.master.wyrecorder.ui;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.annotations.Title;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.common.RecycleViewItemClickListener;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.LiveTypeInfo;
import com.miqtech.master.wyrecorder.entity.SearchWrapper;
import com.miqtech.master.wyrecorder.ui.adapter.SelectGameAdatper;
import com.miqtech.master.wyrecorder.utils.FileUtils;
import com.miqtech.master.wyrecorder.utils.L;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2016/12/23.
 */
@LayoutId(R.layout.activity_select_game)
@Title(titleId = R.string.game_select_title)
public class SelectGameActivity extends BaseAppCompatActivity implements RecycleViewItemClickListener {
    @BindView(R.id.rvGameSelect)
    RecyclerView rvGameSelect;
    @BindView(R.id.ibRight)
    ImageButton ibRight;
    private SelectGameAdatper adapter;
    private List<LiveTypeInfo> mGameInfo = new ArrayList<>();
	private ArrayList<LiveTypeInfo> historys;
    private List<SearchWrapper<Object>> mResult = new ArrayList<>();
    private GridLayoutManager layoutManager;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        initView();
        getHistoryData();
        loadGameInfo();
    }
	
    /**
     * 保存历史数据
     *
     * @return
     */
    private void initView() {
        historys = new ArrayList<LiveTypeInfo>();
        ibRight.setVisibility(View.VISIBLE);
        ibRight.setImageResource(R.drawable.delete_activity);
        hideBack();
        layoutManager = new GridLayoutManager(this, 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (mResult != null && mResult.get(position).type == 0) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });
        rvGameSelect.setLayoutManager(layoutManager);
        adapter = new SelectGameAdatper(this, mResult);
        rvGameSelect.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }
	
    //获取经常玩的游戏类型
    private void getHistoryData() {
        historys = FileUtils.readData();
        addHistoryGames();
    }

    /**
     * 请求分类数据
     */
    private void loadGameInfo() {
        sendHttpRequest(API.GAMETYPE, null);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        Gson gson = new Gson();
        try {
            switch (method) {
                case API.GAMETYPE:
                    mGameInfo = gson.fromJson(object.getJSONArray("object").toString(),
                            new TypeToken<List<LiveTypeInfo>>() {
                            }.getType());
                    addGames();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onFaild(JSONObject object, String method) {
        super.onFaild(object, method);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onError(String errMsg, String method) {
        super.onError(errMsg, method);
        adapter.notifyDataSetChanged();
    }

    private void addHistoryGames() {
        if (historys != null && !historys.isEmpty()){
            mResult.add(0, new SearchWrapper<Object>(SelectGameAdatper.VIEW_TITLE, "最近选择"));
            for(int i = 0; i < 2 && i < historys.size(); i++){
                historys.get(i).setPosition(i);
                mResult.add(new SearchWrapper<Object>(SelectGameAdatper.VIEW_HISTORY_ITEM, historys.get(i)));
            }
        }
    }

    private void addGames() {
        if (mGameInfo != null && !mGameInfo.isEmpty()) {
            mResult.add(new SearchWrapper<Object>(SelectGameAdatper.VIEW_TITLE, "全部游戏"));
            for (int i = 0; i < mGameInfo.size(); i++) {
                mGameInfo.get(i).setPosition(i);
                mResult.add(new SearchWrapper<Object>(SelectGameAdatper.VIEW_ITEM, mGameInfo.get(i)));
            }
        }
        adapter.notifyDataSetChanged();
    }
    @OnClick({R.id.ibRight})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ibRight:
                onBackPressed();
                this.overridePendingTransition(0, R.anim.activity_bottom_out);
                break;
        }
    }
    @Override
    public void onItemClick(View view, int position) {
        //跳转到指定的界面  并保存信息
        LiveTypeInfo mLiveTypeInfo;
		mLiveTypeInfo = (LiveTypeInfo) mResult.get(position).data;
        Bundle bundle = new Bundle();
        if(mLiveTypeInfo != null) {
            savaHistoryData(mLiveTypeInfo);
            bundle.putString("imageUrl", mLiveTypeInfo.getIcon());
            bundle.putString("gameID", mLiveTypeInfo.getId());
            bundle.putString("gameName", mLiveTypeInfo.getName());
            bundle.putString("gameIcon", mLiveTypeInfo.getIcon());
        }
        updateAdatper();
        jumpToActivity(RecorderSettingActivity.class, bundle);
    }

    private void savaHistoryData(LiveTypeInfo mLiveTypeInfo) {
        ArrayList<LiveTypeInfo> tempHistorys = new ArrayList<LiveTypeInfo>();
        if(mLiveTypeInfo != null) {
            tempHistorys.add(mLiveTypeInfo);
            if (historys != null) {
                for (int i = 0; i < historys.size(); i++) {
                    if (!mLiveTypeInfo.getId().equals(historys.get(i).getId())) {
                        historys.get(i).setPosition(i);
                        tempHistorys.add(historys.get(i));
                    }
                }
            }
            historys = tempHistorys;
            FileUtils.writeData(tempHistorys);
        }
    }
    private void updateAdatper() {
        mResult.clear();
		addHistoryGames();
		addGames();
    }
}
